import sys
import os
import threading
from flask import Flask, jsonify, request
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QVBoxLayout, QWidget
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon, QFont

# 导入Flask相关模块
from config.database import db
from model.template_model import Template
from model.log_model import Log
from service.template_service import TemplateService
from dao.template_dao import TemplateDao

# 导入PyQt视图
from views.DataDictionaryView import DataDictionaryView
from config.log_config import AntLogger

# 创建Flask应用
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

# PyQt主窗口类
class MainWindow(QMainWindow):
    """主窗口类"""
    def __init__(self):
        super().__init__()
        self._init_ui()
        AntLogger.info('应用程序启动成功')
    
    def _init_ui(self):
        """初始化界面"""
        self.setWindowTitle('数据管理系统')
        self.setMinimumSize(1000, 700)
        
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(5, 5, 5, 5)
        
        # 创建选项卡部件
        self.tab_widget = QTabWidget()
        self.tab_widget.setTabPosition(QTabWidget.North)
        self.tab_widget.setTabShape(QTabWidget.Rounded)
        self.tab_widget.setDocumentMode(True)
        self.tab_widget.setMovable(True)
        
        # 添加数据字典视图
        self.dictionary_view = DataDictionaryView()
        self.tab_widget.addTab(self.dictionary_view, '数据字典')
        
        # 将选项卡部件添加到主布局
        main_layout.addWidget(self.tab_widget)
        
        # 设置样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f8ff;
            }
            QTabWidget::pane {
                border: 1px solid #87ceeb;
                background-color: #f0f8ff;
                border-radius: 3px;
            }
            QTabBar::tab {
                background-color: #d0e9f5;
                color: #333333;
                border: 1px solid #87ceeb;
                border-bottom: none;
                border-top-left-radius: 4px;
                border-top-right-radius: 4px;
                padding: 8px 12px;
                margin-right: 2px;
                font-weight: bold;
            }
            QTabBar::tab:selected {
                background-color: #87ceeb;
                color: white;
            }
            QTabBar::tab:hover:!selected {
                background-color: #e6f7ff;
            }
        """)

def create_app_dirs():
    """创建应用程序所需目录"""
    # 创建日志目录
    log_dir = os.path.join(os.path.dirname(__file__), 'logs')
    os.makedirs(log_dir, exist_ok=True)
    
    # 创建数据目录
    data_dir = os.path.join(os.path.dirname(__file__), 'data')
    os.makedirs(data_dir, exist_ok=True)

if __name__ == '__main__':
    # 创建应用程序所需目录
    create_app_dirs()
    
    # 在后台线程中启动Flask服务
    flask_thread = threading.Thread(target=start_flask)
    flask_thread.daemon = True  # 设置为守护线程，主程序退出时自动结束
    flask_thread.start()
    
    # 创建PyQt应用程序
    app = QApplication(sys.argv)
    app.setStyle('Fusion')  # 使用Fusion风格
    
    # 设置全局字体
    font = QFont('微软雅黑', 10)
    app.setFont(font)
    
    # 创建主窗口
    window = MainWindow()
    window.show()
    
    # 运行应用程序
    sys.exit(app.exec_())